package com.wanmait.zaisousuo.job;

import com.alibaba.fastjson.JSONObject;
import com.wanmait.zaisousuo.pojo.Article;
import com.wanmait.zaisousuo.pojo.ArticlePraise;
import com.wanmait.zaisousuo.pojo.Userinfo;
import com.wanmait.zaisousuo.service.ArticlePraiseService;
import com.wanmait.zaisousuo.service.ArticleService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class CommontJob {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private ArticlePraiseService articlePraiseService;

    @Resource
    private ArticleService articleService;

    @Scheduled(cron = "0 0 0 * * ?")
    public void updateArticlePraise() {
        Set set = redisTemplate.opsForSet().members("article:praise:set");
        for (Object o : set) {
            Integer id = Integer.parseInt((String) o);
            Integer praiseCount = Integer.parseInt((String) redisTemplate.opsForValue().get("article:" + id + ":praise:count"));
            articleService.updatePraiseCount(praiseCount, id);
        }
    }
    /*
        30分钟添加一次数据
     */
    @Scheduled(cron = "0 0/30 * * * ? ")
    public void updatePraise()  throws NullPointerException
    {
        Integer articleId = null;
        Integer userinfoId = null;
        List<ArticlePraise> articlePraises = new ArrayList<>();
        //每次循环弹出一个数据
        for (int i = 0; i < 20; i++) {
            ArticlePraise articlePraise = new ArticlePraise();
            Article article = new Article();
            Userinfo userinfo = new Userinfo();
            String o = (String) redisTemplate.opsForList().leftPop("article:praise:list");
            JSONObject jsonObject = JSONObject.parseObject(o);
            if (o != null) {
                articleId = Integer.parseInt(String.valueOf(jsonObject.get("articleId")));
                userinfoId = Integer.parseInt(String.valueOf(jsonObject.get("userinfoId")));
                article.setId(articleId);
                userinfo.setId(userinfoId);
                articlePraise.setArticle(article);
                articlePraise.setUserinfo(userinfo);
                articlePraises.add(articlePraise);
            } else {
                break;
            }
        }
        articlePraiseService.insertPraiseCount(articlePraises);
    }

}
